﻿//@ hungconcon
var utility = {
    Main:function () {
        this.replace = function(a,b,c){return a.split(b).join(c);};
        this.$ = function (id) { return document.getElementById(id);};
        this.$$ = function (tagname) { return document.getElementsByTagName(tagname); };
        this.$$$ = function (id, tagname) { return document.getElementById(id).getElementsByTagName(tagname); };
        this.$$$$ = function (li, name) { for(var i=0; i<li.length;i++) if(li[i].name==name){ return li[i];} return null; };
        this.em = function (id) { return document.getElementById(id);};
        this.win = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
        this.ie = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
        this.op = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
        this.ce = (navigator.userAgent.indexOf("Chrome") != -1) ? true : false;
        this.ff = (navigator.userAgent.indexOf("Firefox") != -1) ? true : false;
        this.removeChilds = function(id){try{this.$(id).parentNode.removeChild(this.$(id));}catch(ex){}};
        this.getQuerystring = function(a, b){if (b==null) b='';a = a.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');var r = new RegExp('[\\?&]'+a+'=([^&#]*)');var c = r.exec(window.location.href);return (c == null)?b:c[1];};
        this.getBlogID = function() {var links = document.getElementsByTagName('link');var href = '';for(var i=0; i<links.length; i++) {if(links[i].rel == 'EditURI') {href = links[i].href;break;}}href = href.match(/blogID=([\d]+)/);return href[1];};
        //http://blog.stevenlevithan.com/archives/parseuri
        this.parseUri = function(str){ var o = {strictMode:false,key:["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}}; var uri = {}, m = o.parser[o.strictMode ? "strict" : "loose"].exec(str), i = 14; while (i--){ uri[o.key[i]] = m[i] || ""; } uri[o.q.name] = {}; uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {if ($1) uri[o.q.name][$1] = $2; }); return uri;};
        this.maxlength = function(obj){var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""; if (obj.getAttribute && obj.value.length>mlength) obj.value=obj.value.substring(0,mlength);};
        this.numberComma = function(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); };

    },
    Log:function  () {
        this.trace = function (vas) {
            alert(vas);
        };
        this.o = function (a,b) {
            alert(a+":"+b);
        };
    },
    Open:function () {
        this.id = 0;
        this.name = "";
        this.feature = "";
        this.replace = true;
        this.width = 0;
        this.height = 0;
        this.x = null;
        this.y = null;
        this.reload = function (mes) {
        };
        this.reopen = function () {
            return window.reload();
        };
        this.close = function (mes) {
            window.close();
        };
        this.opener = function (url) {
            return (util.ff) ? window.open(url, this.name, this.feature, this.replace) : window.open(url, "newwin", this.feature);
        };
        this.move = function (obj, w, h, x, y) {
            if (x == null && y == null) {
                x = (screen.width - w) / 2;
                y = (screen.height - h) / 2;
            }
            try {
                obj.moveTo(x, y);
            } catch (ex) {
                log('Error util.move', ex);
            }
        };
        this.parser = function (str) {
            var i = 0;
            var smini = "";
            smini = this.feature;
            var arrays = smini.split(",");
            for (var i = 0; i < arrays.length; i++) {
                if (arrays[i].split("=")[0] == str) {
                    i = parseInt(arrays[i].split("=")[1], 10);
                    break;
                }
            }
            return i;
        };
        this.winopen = function (url) {
            //var token = google.accounts.user.checkLogin(BLOGGER_AUTH_URL);
            this.width = this.parser("width");
            this.height = this.parser("height");
            var solat = this.opener(url);
            this.move(solat, this.width, this.height, this.x, this.y);
            solat.window.location.href = url;
        };
    }
};

var mode_save_view=0;
var BlogPress = {
    service: null,
    blogs: [],
    blogFeeds: [],
    currentBlogNum: 0
};
var BLOGGER_AUTH_URL = "http://www.blogger.com/feeds";
var SPREADSHEETS_URL = "https://spreadsheets.google.com/formResponse";
var REMOTE_IP_ADDRESS  ="http://jsonip.com/?callback=trangtrang.setRemote"; //http://demontunes.com/api/?g=ip&format=json&callback=getIpRemote = getIpRemote.data.ip //addScriptCallBacktoHead("http://jsonip.apppost.com/?callback=getIpRemote");
var SPREADSHEETS_KEY = "formkey=dHBWVGJqVG9RQlcwd2h4MjV5d3plZFE6MQ";
var SPREADSHEETS_KEY_CHALLENGE = "0AkLrBx5yiVaqdERkZnNqbVNOT241VlJ0OWg3b1JHTHc";
var BT_ICON_BACKGROUND_UP     = "http://1.bp.blogspot.com/-RyrGk6zRCFc/TbQ63JE2lnI/AAAAAAAAAGQ/kmKoXQ7I4e8/s320/quantity_top.png";
var BT_ICON_BACKGROUND_DOWN     = "http://3.bp.blogspot.com/-vX4LTL0BvHM/TbQ656hZofI/AAAAAAAAAGY/inr0BjbKPXQ/s320/quantity_down.png";
var LINK_REDIRECT_TO_CART = "http://www.trangtrang.com/p/shoppingcart.html";

var variable_page_press={
    flash:'flash.liveshowpage',
    imgthumb: 'pdthumbimg',
    txtthumb: 'pdthumb',
    htmldata:'entryxml',
    istore:'entry_data_image',
    ithumb:'entry_data_thumb',

    lname:['lsname','lename'],
    sname:['ssname','sename'],

    lprice:['lsprice','leprice'],
    sprice:['ssprice','leprice'],

    lstate:['lsstate','lestate'],
    sstate:['ssstate','sestate'],


    lseril:['lsseril','leseril'],
    sseril:['ssseril','seseril'],

    lcalta:['lscalta','lecalta'],
    scalta:['sscalta','secalta'],

    lmater:['lsmaterial','lematerial'],
    smater:['ssmaterial','sematerial'],

    lsize:['lssize','lesize'],
    ssize:['sssize','sesize'],

    lmade:['lsmade','lemade'],
    smade:['ssmade','semade'],

    lnoted:['lsnoted','lenoted'],
    snoted:['ssnoted','senoted']

};
var administrator = {
    Main:function () {
        this.sugar = new Object();
        try{
            this.sugar = new StateSuggestions();
        }catch(ex){}
        var totalpages = 0;
        this.getcount = function(e){
          return totalpages;
        };
        this.addcount = function(e){
            totalpages += e;
        };
        this.printnow = function(e){

        };
        // Lable name of tag
        this.addnames = function(a){
            try{
                this.sugar.states.push(a);
            }catch(e){}
        }
        this.ctag = function(a,b,c){
            var i= document.createElement(a);
            if(b!=null){
                var t=document.createTextNode(b);
                i.appendChild(t);
            }
            for(d in c){
                var id=document.createAttribute(d);
                id.nodeValue = c[d];
                i.setAttributeNode(id);
            }
            return i;
        }

        this.cselec = function(m,c,d,e,f){
            if(m==1){
                var a=util.$(c);
                var k=a.childNodes;

                var s='';
                for(var i=0;i<k.length;i++){
                    s+=k[i].childNodes[0].nodeValue + ((i<k.length-1)?',':'');
                }
                var b=this.ctag(e,null,{id:d,type:'text',value:s});
                a.parentNode.replaceChild(b,a);
                try{
                    var m=util.$(d);
                    m.style.border='none';
                    //m.style.backgroundColor = '#F6F6F6';
                    m.style.background = 'none';
                    m.style.fontFamily = 'Tahoma';
                    m.style.fontSize = '13px';
                    m.style.color = '#454545';
                    m.style.padding= '0px';
                    m.style.margin= '0px';
                    m.style.paddingBottom= '4px';
                    m.style.marginLeft= '-1px';
                    //m.style.marginTop= '2px';
                }catch(e){
                }

            }
            if(m==0){
                var a=util.$(d);
                var s=a.value;
                var r=s.split(',');

                var b=this.ctag(f,null,{id:c});
                for(var i=0;i<r.length;i++){
                    var op=this.ctag('option',r[i],{});
                    b.appendChild(op);
                }
                a.parentNode.replaceChild(b,a);
            }
        }

        this.cinput = function(m,c,d,e,f){
            if(m==1){
                var a=util.$(c);
                var b=this.ctag(e,null,{id:d,type:'text',value:a.childNodes[0].nodeValue});
                a.parentNode.replaceChild(b,a);

                try{
                    var m=util.$(d);
                    m.style.border='none';
                    //m.style.backgroundColor = '#F6F6F6';
                    m.style.background = 'none';
                    m.style.fontFamily = 'Tahoma';
                    m.style.fontSize = '11px';
                    m.style.color = '#454545';
                    m.style.height= '16px';
                    m.style.width= '250px';
                    m.style.padding= '0px';
                    m.style.marginLeft= '-1px';
                    //m.style.paddingTop= '2px';
                    //m.style.paddingBottom= '2px';
                    //m.style.marginBottom= '1px';
                    m.style.marginTop= '1px';
                }catch(e){}

            }
            if(m==0){
                var a=util.$(d);
                var b=this.ctag(f,a.value,{id:c});
                a.parentNode.replaceChild(b,a);
            }
        }
        this.carea = function(m,c,d,e,f){
            if(m==1){
                var a=util.$(c);
                var b=this.ctag(e,a.childNodes[0].nodeValue,{id:d,cols:35,rows:3});
                a.parentNode.replaceChild(b,a);
            }
            if(m==0){
                var a=util.$(d);
                var b=this.ctag(f,a.childNodes[0].nodeValue,{id:c});
                a.parentNode.replaceChild(b,a);
            }
        }
        this.edit = function(d,e){
            mode_save_view=(mode_save_view==0)?1:0;
            this.cinput(mode_save_view,variable_page_press.sname[0],variable_page_press.sname[1],'input','span');
            this.cinput(mode_save_view,variable_page_press.sprice[0],variable_page_press.sprice[1],'input','span');
            this.cinput(mode_save_view,variable_page_press.sstate[0],variable_page_press.sstate[1],'input','span');
            this.cinput(mode_save_view,variable_page_press.sseril[0],variable_page_press.sseril[1],'input','span');
            this.cinput(mode_save_view,variable_page_press.scalta[0],variable_page_press.scalta[1],'input','span');
            this.cinput(mode_save_view,variable_page_press.smater[0],variable_page_press.smater[1],'input','span');
            this.cselec(mode_save_view,variable_page_press.ssize[0],variable_page_press.ssize[1],'input','select');
            this.cinput(mode_save_view,variable_page_press.smade[0],variable_page_press.smade[1],'input','span');
            this.cinput(mode_save_view,variable_page_press.snoted[0],variable_page_press.snoted[1],'input','span');

            if(mode_save_view==1){
                d.value = 'Cancel';
                // Image in txt input with att hidden
                //try{ var ts=util.$('pdthumb'); ts.setAttribute("type","text"); }catch(e){ }
                try{
                    //sugar.states =sugar.states.unique(); // Cancel prototype unique
                    var a = util.$(variable_page_press.scalta[1]);
                    var oTextboxa = new AutoSuggestControl(a,this.sugar);

                    var b = util.$(variable_page_press.sstate[1]);
                    var sugerstatus = new StateSuggestions();
                        sugerstatus.states.push('Còn hàng');
                        sugerstatus.states.push('Hết hàng');
                    var oTextboxb = new AutoSuggestControl(b,sugerstatus);
                }catch(e){
                    log.o('Error sugar.states','');
                }
            }else{
                d.value = 'Edit';
                //try{var ts=util.util.$('pdthumb'); ts.setAttribute("type","hidden"); }catch(e){ }
            }
        }
        this.saveas = function(spotid){
            var token = google.accounts.user.checkLogin(BLOGGER_AUTH_URL);
            if (token) {
                if(mode_save_view==1)
                    try{
                        this.edit(util.$('editpage'),'');
                    }catch(ex){
                        alert("Error admin.saveas:"+ex);
                    }
                this.insertOrUpdatePostEntry(spotid);
            }else{
                log.o('Save As:','You are not Owner!');
            }
        }
        this.deletePost = function(postids,isback) {
            var portidr = postids.split("_");
            var postid = portidr[1];
            var blogid = util.getBlogID();
            var blogPostHref = 'http://www.blogger.com/feeds/'+blogid+'/posts/default/'+postid;
            var token = google.accounts.user.checkLogin(BLOGGER_AUTH_URL);
            if(window.confirm('Are you sure you want delete?'))
                if (token) {
                    this.deleteEntryLink(blogPostHref,isback);
                }else{
                    log.o('Delete Post:','You are not Owner!');
                }
        }

        this.changeStatus = function(s) {
            //alert(s);
        }
        this.insertOrUpdatePostEntry = function(postid) {
            // Get the values from the form.
            //http://4.bp.blogspot.com
            var title   = util.$(variable_page_press.sname[0]).childNodes[0].nodeValue;

            var categoriesString = util.$(variable_page_press.scalta[0]).childNodes[0].nodeValue;
            var contents = util.$(variable_page_press.htmldata);

            var splite = util.$$$(variable_page_press.htmldata, "a");
            var amore = util.$$$$(splite, "more");
            var more = document.createComment("more");
            amore.parentNode.replaceChild(more,amore);
            var content = HTMLtoXML(contents.innerHTML);

            //alert(content);
            //return;

            var categoriesArray = categoriesString.split(',');
            // Create event object and set relevant properties.
            var blogPostEntry = new google.gdata.blogger.PostEntry();
            blogPostEntry.setTitle(google.gdata.atom.Text.create(title));
            blogPostEntry.setContent(google.gdata.atom.Text.create(content, 'html'));
            for (var c = 0; c < categoriesArray.length; c++) {
                if (categoriesArray[c] != '') {
                    var category = new google.gdata.atom.Category();
                    category.setTerm(categoriesArray[c]);
                    category.setScheme('http://www.blogger.com/atom/ns#');
                    blogPostEntry.addCategory(category);
                }
            }
            var blogid = util.getBlogID();
            if (postid != '') {
                var blogPostHref = 'http://www.blogger.com/feeds/'+blogid+'/posts/default/'+postid;
                BlogPress.service.updateEntry(blogPostHref, blogPostEntry, admin.handleEntryPost, admin.handleError);
            } else { 					// Adding a new post.
                var blogPostHref = 'http://www.blogger.com/feeds/'+blogid+'/posts/default';
                BlogPress.service.insertEntry(blogPostHref, blogPostEntry, admin.handleEntryPost, admin.handleError);
            }
        }
        this.deleteEntryLink = function(blogPostHref,isback){
            if(isback==0){
                BlogPress.service.deleteEntry(blogPostHref, admin.handleDeletePostReload, admin.handleError);
            }
            if(isback==1){
                BlogPress.service.deleteEntry(blogPostHref, admin.handleDeletePostBack, admin.handleError);
            }
        }
        this.handleDeletePostReload = function() {
            admin.changeStatus('Successfully deleted post.');
            //window.location.reload();
            window.location.href = window.location.href;
        }
        this.handleDeletePostBack = function() {
            admin.changeStatus('Successfully deleted post.');
            if(window.history.length==0)
                window.location.href="/";
            else
                window.history.go(-1);
        }
        this.handleEntryPost = function(entryRoot) {
            admin.changeStatus('Successfully publied post.');
            //window.location.reload();
            window.location.href = window.location.href;
        }
        this.handleError = function(error) {
            admin.changeStatus(error.cause ? error.cause.statusText : error.message);
        }
        this.loginOrLogout = function(){
            var token = google.accounts.user.checkLogin(BLOGGER_AUTH_URL);
            if (token!="") {
                google.accounts.user.logout();
                window.location.reload();
            } else {
                google.accounts.user.login(BLOGGER_AUTH_URL);
            }
        }
        this.AuthSub = function () {
            try {
                var token = google.accounts.user.checkLogin(BLOGGER_AUTH_URL);
                var a = util.$("btlogin");
                var b = a.childNodes[0];
                if (token) {
                    var c = document.createTextNode("Đăng xuất");
                        b.parentNode.replaceChild(c, b);
                        a.setAttribute("href", "javascript:admin.loginOrLogout()");
                        BlogPress.service = new google.gdata.blogger.BloggerService('GoogleInc-bloggerOffline-1');
                } else {
                    var c = document.createTextNode("Đăng nhập");
                    b.parentNode.replaceChild(c, b);
                    var homepageUrl = a.getAttributeNode('href').value;
                    a.setAttribute("href","javascript:plopen.winopen('"+homepageUrl+"')");
                }
            } catch (e) {

            }
        };

    }
};

var uploadcontrol = {
    Flash:function(){
        this.name     = '';
        this.id       = '';
        this.swf      = '';
        this.handler  = '';
        this.divid    = '';
        this.div      =  new Object();
        this.variable = new Object();
        this.install = function(w,h,c){
            this.div = util.$(this.divid);
            var so = new SWFObject(this.swf, this.id, w, h, "9", c);
            so.addParam("allowScriptAccess" , "always");
            so.addParam("scriptAccess"      , "always");
            so.addParam("allowNetworking"   , "all");
            so.addParam("quality"           , "high");
            so.addParam("wmode"             , "transparent");
            so.addParam("menu"              , "false");
            so.addParam("allowfullscreen"   , "true");
            for(var key in this.variable) so.addVariable(key,this.variable[key]);
            so.write(this.divid);
            //util.$(this.id).focus();
        };
        this.resetData = function(){
            this.getData();
        };
        this.openPicker = function(value){
            try{
                ulits.visible(true);
            }catch(ex){
                alert("Error.openPicker:"+ex);
            }
        };
        this.setData = function(value){ // Flash Call Out: flash > js > htmn
            util.$('pdthumb').value = value;
            // set image thumbs;
            try{
                var d = util.$("ptdimagethumb");
                var doc = JSON.parse(value);
                uri = util.parseUri(doc[0].thumbnails[4].url);
                d.src = "http://4.bp.blogspot.com"+uri.directory+"h170/"+uri.file;
            }catch(ex){
                alert("Set data to image.ptdimagethumb false!");
            }
        };
        this.getData = function(){      //// Flash Call: flash > js > flash
            var txt = util.$('pdthumb').value;
            if(txt=="") return;
            var data = util.replace(txt,"https","http");
            util.$(this.id)[this.variable.handler+'.'+'setData'](data);
        };
        this.wheelForFF = function(){

        };
        this.addwheel = function (handlers) {
            var id = this.id;
            try {
                if (util.ff || util.ce) {
                    var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";
                    util.$(id).addEventListener(mousewheelevt,function(e){
                        var evt=window.event || e ;//equalize event object
                        var delta=evt.detail? evt.detail*(-120) : evt.wheelDelta;
                        util.$(id)[handlers+".addwheel"](delta);
                        //disable default wheel action of scrolling page
                        if (evt.preventDefault)
                            evt.preventDefault()
                        else
                            return false;
                    },true);
                }
                if (util.ie) {
                    util.$(id).onmouseover = function () {
                        document.onmousewheel = function (event) {
                            try {
                                var delta = 0;
                                if (!event) event = window.event;
                                if (event.wheelDelta) {
                                    delta = event.wheelDelta / 120;
                                    if (window.opera)
                                        delta = -delta;
                                } else if (event.detail) delta = -event.detail / 3;
                                util.$(id)[handlers+".addwheel"](delta);
                            } catch (e) {
                            }
                            return false;
                        };
                    };
                    util.$(id).onmouseout = function () {
                        document.onmousewheel = function (event) {
                            return true;
                        };
                    };
                }
            } catch (e) {
                alert('addwheel:' + e);
            }
        };
    },
    Main:function(){
        var picker;
        this.flhandler = '';
        this.createPicker = function() {
            var a = google.picker.ViewId.PHOTOS;
            var b = google.picker.ViewId.PHOTO_UPLOAD;
            var c = google.picker.Feature.MULTISELECT_ENABLED;
            var d = ulits.pickerCallback;
            picker = new google.picker.PickerBuilder().addView(a).addView(b).enableFeature(c).setCallback(d).build();
            picker.setVisible(false);
        };
        this.callHandler = function(){
            try{
                var opp = eval(this.flhandler);
                    opp.resetData();
            }catch(ex){
                log.o("callHandler:",ex);
            }
        };
        this.pickerCallback = function(e) {
            var b = util.$("pdthumb");
            var d = util.$("ptdimagethumb");
            var c= "";
            var doc;
            var uri;
            if((e.action == google.picker.Action.PICKED)){
                switch (e.viewToken[0]){
                    case google.picker.ViewId.PHOTO_UPLOAD:
                        doc = e.docs;
                        uri = util.parseUri(doc[0].thumbnails[4].url);
                        d.src = "http://4.bp.blogspot.com"+uri.directory+"h170/"+uri.file;
                        c = JSON.stringify(doc);
                        b.value = c;
                        ulits.callHandler();
                    break;
                    case google.picker.ViewId.PHOTOS:
                        doc = e.docs;
                        uri = util.parseUri(doc[0].thumbnails[4].url);
                        d.src = "http://4.bp.blogspot.com"+uri.directory+"h170/"+uri.file;
                        c = JSON.stringify(doc);
                        b.value = c;
                        ulits.callHandler();
                    break;
                    default:break;
                }
            }
        };
        this.visible = function(a){
            if(picker!="undefined")
                picker.setVisible(a);
        };
        this.test = function(e){
        };
    }
};






var shopping = {
    Cache:function(){
        this.ip         = '127.0.0.1';
        this.cname      = '__ttsc'; // trang trang cart cache
        this.fname      = '__ttfc'; // trang trang form cahe
        this.domain     = 'trangtrang.com';
        this.path       = '/';
        this.ship       = 0;
        this.items      = [];
    },
    Form:function(){
       this.name  = '';
       this.mail  = '';
       this.phone = '';
       this.addr  = '';
       this.note  = '';
       this.toString = function () {
           return this.name+','+this.mail+','+this.phone+','+this.addr+','+this.note;
       }
    },
    Cart:function(){
        this.id = '';
        this.img = '';
        this.url = '';
        this.name = '';
        this.size = '';
        //this.tax      = 0;
        this.price    = 0;
        this.quantity = 0;
        this.toString = function () {
            return this.id + ',' +
                this.img + ',' +
                this.url+ ',' +
                this.name + ',' +
                this.size + ',' +
                //this.tax + ',' +
                this.price + ',' +
                this.quantity;
        };
    },
    MiniCart:function(){
        this.id = '';
        this.size = '';
        //this.tax      = 0;
        this.price    = 0;
        this.quantity = 0;
        this.toString = function () {
            return this.id + ',' +
                this.size + ',' +
                //this.tax + ',' +
                this.price + ',' +
                this.quantity;
        };
    },
    Main:function(){
        this.setRemote = function (data) { cartcache.ip = data.ip; };
        this.setCookie = function(name, value, expires, path, domain, secure) {
            var today = new Date();
            today.setTime(today.getTime());
            if (expires) expires = expires * 1000 * 60 * 60 * 24;
            var expires_date = new Date(today.getTime() + (expires));
            document.cookie = name + "=" + escape(value) +
                ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
                ( ( path ) ? ";path=" + path : "" ) +
                ( ( domain ) ? ";domain=" + domain : "" ) +
                ( ( secure ) ? ";secure" : "" );
        };
        this.getCookie = function(a) {
            var b = document.cookie.split(';');
            var c = '', d = '', e = '';
            var g = false;
            for (i = 0; i < b.length; i++) {
                c = b[i].split('=');
                d = c[0].replace(/^\s+|\s+$/g, '');
                if (d == a) {
                    g = true;
                    if (c.length > 1)
                        e = unescape(c[1].replace(/^\s+|\s+$/g, ''));
                    return e;
                }
                c = null;
                d = '';
            }
            if (!g)
                return null;
        };
        this.delCookie = function(name, path, domain) {
            if (this.getCookie(name)) document.cookie = name + "=" +
                ( ( path ) ? ";path=" + path : "") +
                ( ( domain ) ? ";domain=" + domain : "" ) +
                ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
        };

        this.loadCookieOne = function(){
            try {
                $('showquantity').innerHTML = '';
                var b = this.getCookie(cartcache.cname);
                var a = this.getListCart(b);
                var t = 0;
                if (a.length > 0) {
                    this.hideShowShoppingcart(true);

                    cartcache.items = this.findDuplicates(a);
                    for (var i = 0; i < cartcache.items.length; i++)
                        t = t + cartcache.items[i].quantity;
                    try {var k0 = util.$('showquantity');k0.innerHTML = t;k0.setAttribute("href",LINK_REDIRECT_TO_CART);} catch (ex) {}
                    try {var k1 = util.$('clearcookieid');k1.style.visibility = 'visible';k1.setAttribute("onclick", "trangtrang.clearCookieNow();trangtrang.loadCookieOne();");} catch (ex) {}
                } else {
                    this.hideShowShoppingcart(false);

                    try {var k2 = util.$('showquantity');k2.innerHTML = '0';k2.setAttribute("href", "javascript:void(0);");} catch (ex) {}
                    try {var k3 = util.$('clearcookieid');k3.style.visibility = 'hidden';k3.setAttribute("onclick", "trangtrang.clearCookieNow();trangtrang.loadCookieOne();");} catch (ex) {}
                }
            } catch (ex) {
                log.o('Error loadCookieOne:', ex);
            }
            //setTimeout("trangtrang.loadCookieOne",2000);
        };
        this.updateString = function(){
            var a = '';
            for (var i = 0; i < cartcache.items.length; i++) {
                var m = cartcache.items[i];
                a += (i < cartcache.items.length - 1) ? m.toString() + ';' : m.toString();
            }
            this.setCookie(cartcache.cname, a, 10080, cartcache.path, cartcache.domain, '');
            try {this.loadCookieOne(); } catch (ex) {}
        };
        this.setFormCahe = function(a){
            if(a!=null){
                try{this.delCookie(cartcache.fname,cartcache.path, cartcache.domain);}catch(ex){
                    log.o("Error setFormCahe:",ex);
                }
                try{this.setCookie(cartcache.fname, a.toString(), 10080, cartcache.path, cartcache.domain, '');}catch(ex){
                    log.o("Error setFormCahe:",ex);
                }
            }
        };
        this.getFormCahe = function(a){
            var f = null;
            if(a!=null){
                if (a.length > 0){
                    var d = a.split(",");
                    if(d.length > 1){
                        f      = new shopping.Form();
                        f.name = d[0];
                        f.mail = d[1];
                        f.phone= d[2];
                        f.addr = d[3];
                        f.note = d[4];
                    }
                }
            }
            return f;
        };
        this.getListCart = function(a) {
            var c = new Array();
            if (a != null)
                if (a.length > 0) {
                    var b = a.split(";");
                    b.sort();
                    for (var i = 0; i < b.length; i++) {
                        var k = this.getCart(b[i]);
                        c.push(k);
                    }
                }
            return c
        };
        this.findDuplicates = function(a) {
            var b = new Array();
            var c = new Object();
            for (var i = 0; i < a.length; i++) {
                var j = a[i];
                var k = c[j];
                c[j] = (k >= 1) ? (k + 1) : 1;
            }
            for (var m in c) {
                if (c[m] > 1) {
                    var mk = this.getCart(m);
                    mk.quantity = c[m];
                    b.push(mk);
                }
                if (c[m] == 1) {
                    var mk = this.getCart(m);
                    b.push(mk);
                }
            }
            return b;
        }
        this.clearFormNow = function() {
            this.delCookie(cartcache.fname, cartcache.path, cartcache.domain);
        }
        this.clearCookieNow = function() {
            this.delCookie(cartcache.cname, cartcache.path, cartcache.domain);
            cartcache.items = [];
        };
        this.deleteRecord = function(a, b) {
            try {
                var a = this.getCart(a);
                for (var i = 0; i < cartcache.items.length; i++) {
                    var m = cartcache.items[i];
                    if ((a.id == m.id) && (a.size == m.size) && (a.name == m.name)) {
                        cartcache.items.splice(i, 1);
                        break;
                    }
                }
                this.updateString();
            } catch (ex) {
            }
            try {
                var num = b.id.split("_")[1];
                var re = util.$('htcr_' + num);
                re.parentNode.removeChild(re);
            } catch (ex) {
            }
        };
        this.calculerSumNow = function(){
            var a = util.$("total_value_of_production");
            var b = util.$("total_tax_of_production");
            var c = util.$("total_sum_of_production");


            var a_value = 0;
            for (var i = 0; i < cartcache.items.length; i++) {
                var m = cartcache.items[i];
                a_value += (m.quantity * m.price);
            }

            a.innerHTML  =util.numberComma(a_value);
            b.innerHTML  =util.numberComma(Math.ceil(a_value * 0.1));
            c.innerHTML  =util.numberComma(a_value + Math.ceil(a_value * 0.1));

            //var ef = util.$("form_sub_note_10");
            //ef.style.visibility  =(a_value > 5000000)?"hidden":"visible";

        };
        this.updateRecord = function(str, b, d) {
            var re = util.$('htcrq_' + b.id.split("_")[1]);
            var a = this.getCart(str);
            var totaldiv = util.$('totaldiv_' + b.id.split("_")[1]);
            if (d) {
                try {

                    for (var i = 0; i < cartcache.items.length; i++) {
                        var m = cartcache.items[i];
                        if ((a.id == m.id) && (a.size == m.size) && (a.name == m.name)) {
                            m.quantity++;
                            re.innerHTML = m.quantity;
                            totaldiv.innerHTML = util.numberComma(m.quantity * m.price);
                            break;
                        }
                    }
                    this.updateString();
                } catch (ex) {
                    log.o('updateRecord 1:',ex.messager);
                }
            } else {
                try {
                    var e = false;
                    for (var i = 0; i < cartcache.items.length; i++) {
                        var m = cartcache.items[i];
                        var sum;
                        if ((a.id == m.id) && (a.size == m.size)) {
                            if (m.quantity == 1)
                                return true;
                            m.quantity--;
                            re.innerHTML = m.quantity;
                            totaldiv.innerHTML = util.numberComma(m.quantity * m.price);
                            e = (m.quantity >= 1) ? false : true;
                            if (e) {
                                this.deleteRecord(str, b);
                            } else {
                                this.updateString();
                            }
                            break;
                        }
                    }
                } catch (ex) {
                    log.o('updateRecord 2:',ex.messager);
                }
            }

             this.calculerSumNow();

        };
        this.inertCard  = function(g, b){
            var a = this.getCart(g);
            var c = true;
            var d = false;
            if (b) {
                for (var i = 0; i < cartcache.items.length; i++) {
                    var m = cartcache.items[i];
                    if ((a.id == m.id) && (a.size == m.size)) {
                        m.quantity++;
                        c = false;
                        break;
                    }
                }
                if (c) {
                    cartcache.items.push(a);
                }
            } else {
                for (var i = 0; i < cartcache.items.length; i++) {
                    var m = cartcache.items[i];
                    if ((a.id == m.id) && (a.size == m.size)) {
                        m.quantity--;
                        d = (m.quantity >= 1) ? false : true;
                        if (d) {
                            cartcache.items.splice(i, 1);
                        }
                        break;
                    }
                }
            }
        };
        this.getCart    = function(a) {
            var d       = a.split(",");
            var c       = new shopping.Cart();
            c.id    = d[0];
            c.img   = d[1];
            c.url   = d[2];
            c.name  = d[3];
            c.size  = d[4];
            //c.tax   = parseInt(d[5]);
            c.price = parseInt(d[5]);
            c.quantity = parseInt(d[6]);
            return c;
        };
        this.addToCart = function(postids,isback){
            var portidr = postids.split("_");
            var postid = portidr[1];
            var blogid = util.getBlogID();
            var statu=util.$('ssstate').childNodes[0].nodeValue;
            //if(statu=='Hết hàng'){ alert('Đã hết hàng!'); }else{
                var id   = blogid+"-"+postid;

                var img="";
                var json = util.$("pdthumb").value;
                if(json!=""){
                    var doc = JSON.parse(json);
                    var uri = util.parseUri(doc[0].thumbnails[4].url);
                    img  = "http://4.bp.blogspot.com"+uri.directory+"h72/"+uri.file;
                }
                var url  = document.location.href;
                var name = util.$(variable_page_press.sname[0]).childNodes[0].nodeValue;
                var opps = util.$(variable_page_press.ssize[0]);
                var size =(util.ie)?(opps.options[opps.selectedIndex].text):(opps.options[opps.selectedIndex].value);
                var price= util.$(variable_page_press.sprice[0]).childNodes[0].nodeValue.split(' ')[0].replace(/\,/g,'');
                var quantity = 1;
                var str = id + ',' + img + ',' +url+ ',' + name + ',' + size + ',' + price + ',' + quantity;
                this.inertCard(str,true);
                this.updateString();
                this.loadCookieOne();
                alert('Thêm vào giỏ hàng thành công');
            //}
        };
        this.duplicateCartList = function(a){
            var b = new Array();
            for (var i = 0; i < a.length; i++) {
                var c = a[i];
                var m   = new shopping.MiniCart();
                m.id = c.id;
                m.size = c.size;
                //m.tax = c.tax;
                m.price = c.price;
                m.quantity = c.quantity;
                b.push(m);
              }
            return b;
        };
        this.duplicateCartString = function(a){
            var s = "";
            for (var i = 0; i < a.length; i++) {
                var c = a[i];
                var m   = new shopping.MiniCart();
                    m.id = c.id;
                    m.size = c.size;
                    m.price = c.price;
                    m.quantity = c.quantity;
                s += (m.toString() + ((i < (a.length-1))?"|":""));
            }
            return s;
        };
        this.sendToServer = function() {

            var b = this.getCookie(cartcache.cname);
            var a = this.getListCart(b);
            if (a.length > 0) {
                //cartcache.items = this.findDuplicates(a);
                if(cartcache.items.length == 0){
                    alert("Data null!"); return;
                }

                //var dupli = this.duplicateCartList(cartcache.items);
                //var d = JSON.stringify(dupli);

                var d = this.duplicateCartString(cartcache.items);
                var form_sub_data   = encodeURIComponent(d);
                var form_sub_name   = util.$("form_sub_name").value;
                var form_sub_mail   = util.$("form_sub_mail").value;
                var form_sub_phone  = util.$("form_sub_phone").value;
                var form_sub_add    = util.$("form_sub_add").value;
                var form_sub_note   = util.$("form_sub_note").value;
                var form_sub_res    = util.$("recaptcha_response_field").value;

                var check_oaddress    = util.$("sendto_another_address").checked;

                var form_sub_chang  = (RecaptchaState!='undefined')?((RecaptchaState.challenge!="")?RecaptchaState.challenge:""):"";

                if (d == "") { alert("Pls add some of the goods to here!"); return; }

                if (form_sub_name == "" && form_sub_mail == "") {
                    alert("Check out form!");
                    return;
                }

                var u = SPREADSHEETS_URL;
                var v = SPREADSHEETS_KEY;
                v += "&entry.0.single=" + form_sub_data;

                v += "&entry.1.single=" + form_sub_name;
                v += "&entry.2.single=" + form_sub_mail;
                v += "&entry.3.single=" + form_sub_phone;
                v += "&entry.4.single=" + form_sub_add;
                v += "&entry.5.single=" + form_sub_note;

                v += "&entry.6.single=" + form_sub_res;
                v += "&entry.7.single=" + form_sub_chang;
                v += "&entry.8.single=" + cartcache.ip;


                if(check_oaddress){
                    var form_ship_name  = util.$("form_ship_name").value;
                    var form_ship_mail  = util.$("form_ship_mail").value;
                    var form_ship_phone = util.$("form_ship_phone").value;
                    var form_ship_add   = util.$("form_ship_add").value;

                     if(form_ship_name==""){
                         alert("Kiểm tra lại tên của người nhận!");
                         return;
                     }
                    if(form_ship_phone==""){
                        alert("Kiểm tra lại điện thoại của người nhận!");
                        return;
                    }
                    if(form_ship_phone==""){
                        alert("Kiểm tra lại địa chỉ của người nhận!");
                        return;
                    }
                    var oaddress = {n:form_ship_name,m:form_ship_mail,p:form_ship_phone,d:form_ship_add};
                    var newoaddress = encodeURIComponent(JSON.stringify(oaddress));
                    v += "&entry.9.single=" + newoaddress;
                }

                //alert(v);

                try{
                    var f      = new shopping.Form();
                        f.name = util.$("form_sub_name").value;
                        f.mail = util.$("form_sub_mail").value;
                        f.phone= util.$("form_sub_phone").value;
                        f.addr = util.$("form_sub_add").value;
                        f.note = util.$("form_sub_note").value;
                    this.setFormCahe(f);
                }catch(ex){
                    log.o("Error sendToServer.setCacheForm:",ex);
                }
                var src =  u + "?" + v;

                //alert(src.length);
                //return;

                util.$("hungconcon").src = src;
                this.checkIframeLoading();
            }
        };
        this.checkChallenge = function(){
            try{
                trangtrang.totalrequest++;
                //util.$("form_sub_note").value +=" > "+trangtrang.totalrequest;
                var form_sub_chang  = (RecaptchaState!='undefined')?((RecaptchaState.challenge!="")?RecaptchaState.challenge:""):"";
                var query_challenge = new google.visualization.Query('http://spreadsheets.google.com/tq?key='+SPREADSHEETS_KEY_CHALLENGE+'&pub=1');
                    query_challenge.setQuery("SELECT B WHERE A='"+form_sub_chang+"'");
                    query_challenge.send(trangtrang.handleQueryResponse);
            }catch(ex){
                alert(ex);
            }
        };
        this.streamloading = new Object();
        this.totalrequest = 0;
        this.handleQueryResponse = function(response) {
            var json = JSON.parse(response.getDataTable().toJSON());
            if(json.rows==""){
                trangtrang.streamloading = setTimeout(trangtrang.checkChallenge, 1000);
                if(trangtrang.totalrequest >= 20){
                    clearTimeout(trangtrang.streamloading);
                    trangtrang.totalrequest = 0;
                    alert("Server hiện đang quá tải!");
                }
                return;
            }
            if(json.rows[0].c[0].v == 0){
                alert("Sai mã xác thực. Xin kiểm tra lại!");
                try{
                    Recaptcha.reload();
                }catch(ex){
                }
                return;
            }
            if(json.rows[0].c[0].v == 1){
                //alert(json.rows[0].c[0].f);
                try{
                    Recaptcha.reload();
                }catch(ex){
                }
                alert("Đặt hàng thành công!.");
            }
        };
        this.checkIframeLoading = function() {
            var a = util.$('hungconcon');
            if (util.ie && !window.opera) {
                a.onreadystatechange = function(){
                    if (a.readyState == "complete"){
                        trangtrang.checkChallenge();
                    }
                };
            } else {
                a.onload = function(){
                    trangtrang.checkChallenge();
                };
            }
        };
        this.addScriptCallBacktoHead =function(url) {
            try {var gd = document.createElement('script');gd.type = 'text/javascript';gd.src = url;var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(gd, s);} catch (ex) {}
        };
        this.cartCacheFormUser = function(){
            var f0 = this.getCookie(cartcache.fname);
            if(f0!=null){
                var f1 = this.getFormCahe(f0);
                if(f1!=null){
                    try{
                        util.$("form_sub_name").value  = f1.name;
                        util.$("form_sub_mail").value  = f1.mail;
                        util.$("form_sub_phone").value = f1.phone;
                        util.$("form_sub_add").value   = f1.addr;
                        util.$("form_sub_note").value   = f1.note;
                    }catch(ex){
                        log.o("Error loadCookiePrivete.getFormCahe fill to form",ex);
                    }
                }
            }
        };
        this.hideShowShoppingcart = function(ble){
            var a = util.$("shopping_cart_transaction");
            var b = util.$("shopping_cart_non_transaction");
            if(a==null || b==null) return;
            if(ble){
                a.style.display = "inline";
                b.style.display = "none";
            }else{
                a.style.display = "none";
                b.style.display = "inline";
            }
        };
        this.duplicateForm = function(){

        };
        this.loadCookiePrivete = function() {
            try{
                this.addScriptCallBacktoHead(REMOTE_IP_ADDRESS);

                this.cartCacheFormUser();

                var b = this.getCookie(cartcache.cname);
                var a = this.getListCart(b);
                if (a.length > 0) {

                   this.hideShowShoppingcart(true);

                    cartcache.items = this.findDuplicates(a);
                    var table = $('datagrid');
                    var tbody = document.createElement('tbody');
                    tbody.setAttribute("id", "databodyview");



                    for (var i = 0, j = 1; i < cartcache.items.length; i++, j++) {
                        var c = cartcache.items[i];
                        var color = (i % 2 == 0) ? 'odd' : 'even';
                        var tr = document.createElement('tr');
                        tr.setAttribute("id", "htcr_" + i);

                        this.addRowCell(tr, color, document.createTextNode(j));		//c.id

                        var img = new Image();
                        img.setAttribute("id", "htcrfx_" + i);
                        img.id = "htcrfx_" + i;

                        img.src = c.img; //'http://4.bp.blogspot.com/-uYUOs7ajQvE/T2QJQZIb-2I/AAAAAAAAACA/ZDljrXhR2W8/s72/ao1.jpg';

                        img.style.verticalAlign = "middle";
                        img.style.textAlign = "center";
                        img.alt = c.name;

                        this.addRowCell(tr, color,img);

                        var a0 = document.createElement('a');
                        a0.setAttribute("href", c.url);
                        a0.appendChild(document.createTextNode(c.name));

                        this.addRowCell(tr, color, a0);
                        //this.addRowCell(tr, color, document.createTextNode(c.name));
                        this.addRowCell(tr, color, document.createTextNode(c.size));
                        this.addRowCell(tr, color, document.createTextNode(util.numberComma(c.price)));

                        var spqtemp = document.createElement('div');
                        spqtemp.style.backgroundColor = "#FFFFFF";
                        var spqa = document.createElement('div');
                        spqa.setAttribute("id", "htcrq_" + i);
                        spqa.style.backgroundColor = "#FFFFFF";
                        spqa.style.position = 'relative';
                        spqa.style.left = '50%';
                        spqa.style.cssFloat = 'left';
                        spqa.style.styleFloat = 'left';
                        spqa.style.paddingTop = '4px';
                        spqa.appendChild(document.createTextNode(c.quantity));
                        spqtemp.appendChild(spqa);


                        var qdiv = document.createElement('div');
                        qdiv.style.position = 'relative';
                        qdiv.style.width = '10px';
                        qdiv.style.cssFloat = 'right';
                        qdiv.style.styleFloat = 'right';


                        var qint = document.createElement('input');
                        qint.setAttribute('type', "button");
                        qint.setAttribute("id", "htcrt_" + i);
                        qint.setAttribute("onclick", "trangtrang.updateRecord(\"" + c.toString() + "\",this,true)");
                        if (util.ie) qint.onclick = function (e) { trangtrang.updateRecord(c.toString(), this, true); };
                        qint.style.position = 'relative';
                        qint.style.cssFloat = 'left';
                        qint.style.styleFloat = 'left';
                        qint.style.width = '9px';
                        qint.style.height = '10px';
                        qint.style.border = '0px';
                        qint.style.backgroundImage = "url('"+BT_ICON_BACKGROUND_UP+"')";
                        qint.style.backgroundRepeat = 'no-repeat';
                        qint.style.cursor = "hand";
                        qint.style.cursor = "pointer";
                        qint.style.backgroundColor = 'transparent';

                        var qind = document.createElement('input');
                        qind.setAttribute('type', "button");
                        qind.setAttribute("id", "htcrd_" + i);
                        qind.setAttribute("onclick", "trangtrang.updateRecord(\"" + c.toString() + "\",this,false)");
                        if (util.ie) qind.onclick = function (e) { trangtrang.updateRecord(c.toString(), this, false); };

                        qind.style.position = 'relative';
                        qind.style.cssFloat = 'left';
                        qind.style.styleFloat = 'left';
                        qind.style.width = '9px';
                        qind.style.height = '10px';
                        qind.style.border = '0px';
                        qind.style.backgroundImage = "url('"+BT_ICON_BACKGROUND_DOWN+"')";
                        qind.style.backgroundRepeat = 'no-repeat';
                        qind.style.cursor = "hand";
                        qind.style.cursor = "pointer";
                        qind.style.backgroundColor = 'transparent';

                        qdiv.appendChild(qint);
                        qdiv.appendChild(qind);

                        spqtemp.appendChild(qdiv);
                        this.addRowCell(tr, color, spqtemp);



                        var totaldiv = document.createElement('div');
                        totaldiv.setAttribute("id", "totaldiv_" + i);


                        totaldiv.appendChild(document.createTextNode(util.numberComma(c.quantity * c.price)));


                        this.addRowCell(tr, color, totaldiv);


                        var a1 = document.createElement('a');
                        a1.setAttribute("id", "htcrx_" + i);
                        a1.setAttribute("href", "javascript:;");
                        a1.setAttribute("onclick", "trangtrang.deleteRecord(\"" + c.toString() + "\",this)");
                        if (util.ie)
                            a1.onclick = function(){trangtrang.deleteRecord(c.toString(),this); }
                        a1.appendChild(document.createTextNode("x"));
                        this.addRowCell(tr, color, a1);

                        tbody.appendChild(tr);
                    }
                    table.appendChild(tbody);

                    this.calculerSumNow();
                }else{
                    this.hideShowShoppingcart(false);
                }
            }catch(ex){
                log.o("Error home.card.loadCookiePrivete:",ex);
            }
        };
        this.tableCenter = function(a,w,h){
            var ta = document.createElement('table');
            ta.setAttribute("cellpadding", "0");
            ta.setAttribute("cellspacing", "0");
            ta.border = "0";
            ta.cellPadding = "0";
            ta.cellSpacing = "0";
            ta.width = "100%";
            ta.height = "100%";
            var tb = document.createElement('tbody');
            var tr = document.createElement('tr');
            var td = document.createElement('td');
            td.style.width  = w+"px";
            td.style.height = h+"px";
            td.style.textAlign     = "center";
            td.style.verticalAlign = "middle";
            td.appendChild(a);
            tr.appendChild(td);
            ta.appendChild(tr);

            return ta;
        };
        this.addRowCell = function(tr, classname, content) {
            var td = document.createElement('td');
            td.style.textAlign     = "center";
            td.style.verticalAlign = "middle";
            td.style.borderStyle = "solid";
            td.style.borderWidth = "1px";
            td.style.borderColor = "#DBD8D8";
            if (classname != '')
                td.className = classname;
            td.appendChild(content);
            tr.appendChild(td);
        };

    }
};









var util    = new utility.Main();
var log     = new utility.Log();
var plopen  = new utility.Open();
    plopen.name     = "google.account";
    plopen.replace  = true;
    plopen.feature  ="left=0,top=0,right=0,down=0,resizable=0,scrollbars=0,location=0,status=0,width=500,height="+((util.ce)?"600":"500");

/**
 * Page.admin.AuthSub call from page
 */
var admin   = new administrator.Main();
// upload image to server
var ulits   = new uploadcontrol.Main();
/**
 * View image from server to LiveShow
 * set Wheel on ManagerWheel.as
 */
var romakaty= new uploadcontrol.Flash();

var cartcache  = new shopping.Cache();
var trangtrang = new shopping.Main();

